import { Service } from "egg";
import jws from "jws";
import { compareSync, hashSync } from "bcryptjs";
import crypto from "crypto";
import { AuthenticationError } from "apollo-server-koa";

export type ISub = {
  adminId: string;
  source: any;
};

export default class EncryptionService extends Service {
  /**
   * 生成用户授权令牌
   * @param userId 用户id
   */
  generateToken(sub: ISub) {
    const { config } = this.app;

    // 生成授权令牌
    return jws.sign({
      header: { alg: "HS256" },
      payload: {
        // iss: config.DOMAIN_NAME,
        sub,
        // 受众：取得并存储 JWT 的客户端。 TODO: 有网页客户端时，增加客户端网址 可从原始请求取得
        // aud: `WECHAT_MINI_PROGRAM:APP_ID:${config.wechatMiniProgram.APP_ID}`,
        iat: Math.round(new Date().getTime() / 1000),
      },
      secret: config.jwt.SECRET,
    });
  }

  /**
   * 解密token
   * @param token
   */
  decodeToken(token: string) {
    const signature = token.split("Bearer ")[1];
    if (!signature) {
      console.log(token);
    }

    const { payload } = jws.decode(signature);

    // 控制台token
    const verify = jws.verify(signature, "HS256", this.config.jwt.SECRET);
    if (!verify) {
      throw new AuthenticationError("token Error");
    }
    return JSON.parse(payload);
  }

  /**
   * 密码加密
   * @param password 需要加密的密码
   */
  getPasswordHash(password: any) {
    return hashSync(password, 10);
  }

  /**
   * 验证密码是否正确
   * @param password 密码
   * @param passwordHash 加密的密码
   */
  comparePasswordHash(password: any, passwordHash: string) {
    return compareSync(password, passwordHash);
  }
}
